package com.example.captcha;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/admin")
public class KaptchaController {
    private static final String ADMIN_KAPTCHA_SESSION_KEY = "ADMIN_KAPTCHA_SESSION_KEY";
    private static final String ADMIN_KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60 * 1000;

    @RequestMapping("/check")
    public boolean check(String inputCaptcha, HttpSession session) {
        if (!StringUtils.hasLength(inputCaptcha)) {
            return false;
        }
        String capText = (String) session.getAttribute(ADMIN_KAPTCHA_SESSION_KEY);
        Date data = (Date) session.getAttribute(ADMIN_KAPTCHA_SESSION_DATE);

        if (capText.equalsIgnoreCase(inputCaptcha)) {
            if (data != null && (System.currentTimeMillis() - data.getTime()) < TIME_OUT) {
                return true;
            }
        }

        return false;
    }
}
